<?php
class M_order extends CI_Model
{
	private $table_name = "orders";
	private $table_book = "book_bank";
	private $table_book_subject = "subject";
	public function __construct()
	{
		parent::__construct();
	}
	
	public function insertOrder($userid, $orderid, $bookid, $price, $qty = 1, $pdt = '')
	{
		$arr = array('cust_order_id' => $orderid, 'id_user' => $userid, 'price' => $price, 'id_book' => $bookid, 'qty' => $qty, 'pdt' => $pdt);
		$this->db->insert($this->table_name, $arr);
		return $this->db->insert_id();
	}
	
	public function getOrdersOfUserId($userid, $limitStart = FALSE, $limitEnd = FALSE)
	{
		$this->generateOrdersQuery($userid, $limitStart, $limitEnd);
		return $this->db->get();
	}
	
	public  function getOrderCountUserId($userid)
	{
		$res = $this->generateOrdersQuery($userid);
		$count = $res->num_rows();
		$res->free_result();
		return $count; 
	}
	
	private function generateOrdersQuery($userid, $limitStart = FALSE, $limitEnd = FALSE)
	{
		$this->db->from($this->table_name);
		$this->db->join($this->table_book, $this->table_book . ".id = " . $this->table_name . ".id_book", 'left');
		$this->db->where(array('is_deleted'=>0, 'id_user' => $userid));
		$this->db->order_by($this->table_name . ".date_of_order", 'desc');
		if($limitStart && $limitEnd) $this->db->limit($limitStart, $limitEnd);
		elseif ($limitStart) $this->db->limit($limitStart);
		elseif ($limitEnd) $this->db->limit(0, $limitEnd);
	}
}